import random
import time
import string
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
#  storage about stones
from mc import *

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/html'
    self.response.out.write('This is a GomokuOnline Server.If you want to try this game,please visit <a href="http://www.google.com/ig/directory?url=hosting.gmodules.com/ig/gadgets/file/114147862690613182352/GomokuOnline.xml">add to iGoogle</a>')

# First to RequestRandom to Create a Newgame
class Creategame(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/html'
    # create a random number
    rdnum = int(time.strftime("%Y%m%d%H%M%S")) | random.randint(10000000,99999999)
    rdnum = str(rdnum)
    self.response.out.write(rdnum)
    us = isActive()
    us.rdnum = rdnum
    us.CreatorIp = str(self.request.remote_addr)
    us.put()

# For Creator to wait player 
class Waitforjoin(webapp.RequestHandler):
  def get(self):
    rdnum = self.request.get("rdnum")
    us = db.GqlQuery("select * from isActive where rdnum=:radnum",radnum=rdnum)
    p = us.get()
    if not p:
      self.response.out.write("no game create")
      return 0
    if str(p.CreatorIp) != str(self.request.remote_addr):
      self.response.out.write("You aren't player.")
      return 0
    elif str(p.PlayerIp) != "None":
      self.response.out.write("1")
    else:
      self.response.out.write("0")

class Joingame(webapp.RequestHandler):
  def get(self):
    rdnum = self.request.get("rdnum")
    us = db.GqlQuery("select * from isActive where rdnum=:radnum",radnum=rdnum)
    try:
      p = us.get()
      if not p:
        self.response.out.write("2")
        return 0
      p.PlayerIp = str(self.request.remote_addr)
      p.put()
      self.response.out.write("1")
    except:
        #no Creator found.
      self.response.out.write("2")

    
class Stonedown(webapp.RequestHandler):
  def get(self):
    rdnum = self.request.get("rdnum")
    flag = self.request.get("flag")
    stone = self.request.get("stone")
    us = db.GqlQuery("select * from isActive where rdnum=:radnum",radnum=rdnum)
    try:
      p = us.get()
      if not p:
        self.response.out.write("2")
      if int(flag) == 1:
        if str(p.CreatorIp) != str(self.request.remote_addr):
          self.response.out.write("You aren't player.")
          return 0
        # White
      elif int(flag) == 0:
        if str(p.PlayerIp) != str(self.request.remote_addr):
          self.response.out.write("You aren't player.")
          return 0
      else:
        self.response.out.write("error.You aren't player.")
        return 0
    except:
      self.response.out.write("error.no Game")
      return 0
    sd = stoneDatastore()
    sd.rdnum = rdnum
    sd.flag = flag
    sd.x_y = stone
    sd.endtime = int(time.time())
    sd.put()
    self.response.out.write("1")

class getNext(webapp.RequestHandler):
  def get(self):
    rdnum = self.request.get("rdnum")
    flag = self.request.get("flag")
    uss = db.GqlQuery("select * from stoneDatastore where rdnum=:radnum \
    order by endtime desc limit 1",radnum=rdnum)
    p2 = uss.get()
    us = db.GqlQuery("select * from isActive where rdnum=:radnum",radnum=rdnum)
    p = us.get()
    if not p:
      self.response.out.write("2")
    if not p2:
      self.response.out.write("2")
    if int(flag) == 1:
      if str(p.CreatorIp) != str(self.request.remote_addr):
        self.response.out.write("You aren't creator.")
        return 0    
        # White
    elif int(flag) == 0:
      if str(p.PlayerIp) != str(self.request.remote_addr):
        self.response.out.write("You aren't player.")
        return 0
    else:
      self.response.out.write("error.You aren't player.")
      return 0
    res = str(p2.x_y)
    self.response.out.write("1:"+res)
      

ROUTE = [('/', MainPage),
         ('/creategame',Creategame),
         ('/joingame',Joingame),
         ('/stonedown',Stonedown),
         ('/waitforjoin',Waitforjoin),
         ('/getnext',getNext)]

application = webapp.WSGIApplication(ROUTE,debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()